// pages/selection_res/selection_res.js
import Dialog from '@vant/weapp/dialog/dialog';

const app = getApp()
// const globalCountDown = 15 * 60 * 1000
const globalCountDown = 15 * 60 * 1000
const db = wx.cloud.database()

Page({

  /**
   * 页面的初始数据
   */
  data: {
    id: '',
    userPhone: '',
    countDown: globalCountDown,
    stop: false,
    movieId: '',
    movieName: '',
    cinemaName: '',
    cinemaId: '',
    room: '',
    selectedSeat: [],
    time: '',
    price: '',
    poster: '',
    canSubmit: false,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    
  },

  /**
   * 生命周期函数--监听页面显示
   */
  async onShow() {
    this.setData({
      userPhone: app.globalData.userPhone,
      stop: false,
      countDown: globalCountDown,
      canSubmit: false
    })
    let pages = getCurrentPages(); 
    let currentPage = pages[pages.length-1];
    var options = currentPage.options
    var selectedSeat = JSON.parse(options.selectedSeat)
    var sessionId = options.id
    var that = this
    await db.collection('session_info').where({
      _id: sessionId
    }).get().then(res => {
      that.setData({
        id: sessionId,
        cinemaId: res.data[0].cinemaId,
        movieId: res.data[0].movieId,
        time:  res.data[0].date + ' ' + res.data[0].startTime + '-' + res.data[0].endTime,
        room: res.data[0].room,
        price: res.data[0].price
      })
    })

    await db.collection('cinema').where({
      _id: that.data.cinemaId
    }).get().then(res => {
      that.setData({
        cinemaName: res.data[0].funTitle,
        selectedSeat: selectedSeat
      })
    })

    await db.collection('movies').where({
      _id: that.data.movieId
    }).get().then(res => {
      that.setData({
        movieName: res.data[0].title,
        poster: res.data[0].poster
      })
    })

    this.setData({ canSubmit: true })
    this.timeOut()
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {
    this.setData({stop: true})
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    this.setData({stop: true})
  },

  delay(milSec) {
    return new Promise(resolve => {
      setTimeout(resolve, milSec)
    })
  },

  async onSubmit(e) {
    if (!this.data.canSubmit) {
      return
    }

    // 原子支付
    console.log("支付")
    var that = this
    var selectedSeat = this.data.selectedSeat
    var id = this.data.id
    var date = new Date()
    var orderInfo = {
      movieId: this.data.movieId,
      movieName: this.data.movieName,
      orderSessionId: id,
      phone: app.globalData.userPhone,
      lastname: app.globalData.userName,
      price: selectedSeat.length * this.data.price,
      seat: selectedSeat,
      orderDate: date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + date.getDate() + ' ' + date.getHours() + ':' + date.getMinutes(),
      openid: app.globalData.openid
    }

    await wx.cloud.callFunction({
      name: 'buy_ticket_with_transaction',
      data: {
        id: id,
        selectedSeat: selectedSeat,
        orderInfo: orderInfo
      },
      success: res => {
        console.log(res)
        if (res.result.status) {
          wx.showToast({
            title: '订票成功',
            icon: 'success',
            duration: 1000
          })
        } else {
          wx.showToast({
            title: '订票失败',
            icon: 'error',
            duration: 1000
          })
        }
      },
      fail: err => {
        console.log(err)
      },
    })

    await this.delay(1000)
    wx.navigateBack()
  },

  /**
   * 倒计时退出
   */
  async timeOut() {
    for (let i = 0; i * 1000 < globalCountDown; ++i) {
      if (this.data.stop) {
        break
      }
      
      await this.delay(1000)
    }
    Dialog.alert({
      title: '支付超时，该订单已失效',
      message: '请重新购买',
    }).then(() => {
      wx.navigateBack()
    });
  },
})